<?php
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestSms extends RestController {
  public function getrandchar($len) {
    $chars = array (
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9" 
    );
    $charslen = count ( $chars ) - 1;
    shuffle ( $chars );
    $output = "";
    for($i = 0; $i < $len; $i ++) {
      $output .= $chars [mt_rand ( 0, $charslen )];
    }
    return $output;
  }

 
  public function create_mobile_code() {

    $this->checkPlugin();

    $this->load->language ( 'sms/chengyu' );
    
    $this->load->model ( 'account/smsmobile' );
    
    $this->load->model ( 'account/customer' );
    
    $json = array('success' => false);

    if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
      
      $requestjson = file_get_contents('php://input');
    
      $requestjson = json_decode($requestjson, true);

      $post    = $requestjson;

      if ((utf8_strlen ( trim ( $post ['telephone'] ) ) != 11) || (! is_numeric ( $post ['telephone'] ))) {
        $json ['error']['warning'] = $this->language->get ( 'error_telephone' );
      }
      
      // if telephone already registered:
      // if ($this->model_account_customer->getTotalCustomersByTelephone ( $post ['telephone'] )) {
      //   $json ['error']['warning'] = $this->language->get ( 'error_telephone_registered' );
      // }
      
      $data = $this->model_account_smsmobile->getIdBySmsMobile ( trim ( $post ['telephone'] ) );
      
      //同一个用户发送验证码每天不能超过两次,每天发送验证码总条数不超过100的验证 by ypj at 2018.4.20 
      // if($this->model_account_smsmobile->checkSendCodeNum( trim($post ['telephone'] ) )){
      //     $json ['error']['warning'] = $this->language->get ( '验证码发出次数达到上限！' ); 
      // }
      // end
      if ($data && $data ['create_time']) {
        $create_time = strtotime ( $data ['create_time'] );

        if (time () - $create_time < 60) {
          $json ['error']['warning'] = $this->language->get ( 'error_time' );
        }
      }
      if (! isset ( $json ['error'] )) {
        $verify_code = $this->getrandchar ( 6 );
        
        $this->model_account_smsmobile->deleteSmsMobile ( trim ( $post ['telephone'] ) );
        
        $this->model_account_smsmobile->addSmsMobile ( trim ( $post ['telephone'] ), $verify_code );
        
        $post_data = array ();
        $appId = $this->config->get ( 'tianyi_appid' );
        $appSecret = $this->config->get ( 'tianyi_appsecret' );
        $templateId = $this->config->get ( 'tianyi_templateid' );
        // $post_data['content'] = urlencode(sprintf($this->language->get('text_content'), $verify_code));

        $template_param = json_encode ( array (
            "code" => $verify_code,
            "time" => 60
        ) );
        $res = self::sendSmsV2($appId, $appSecret, $templateId, trim ( $post ['telephone'] ), $template_param);
//保存注册验证码的短信接口日志，便于排查异常
$this->load->model('tool/sms_log');
$log = array(
    'telphone' => trim($post['telephone']),
    'date_added' => date ( 'Y-m-d H:i:s' ),
    'get_token_return' => $res['tokenReturn'],
    'template_id' => $templateId,
    'send_info' => json_encode($template_param),
    'send_return' => $res['sendReturn'],
    'return_status' => ('successful' == $res['returnStatus'])?1:0,
);
$this->model_tool_sms_log->saveData($log);
//保存注册验证码的短信接口日志，便于排查异常
        if($res['returnStatus'] == 'successful'){
          $json ['success'] = true;
          $json ['info'] = $this->language->get ( 'text_success' );
        }
        else{
          $json ['error']['warning'] = $res['returnStatus'];
        }
      }
            
    }else {
        $json["error"]['warning']    = "Only POST request method allowed";
        $json["success"]  = false;
    }

    if ($this->debugIt) {
      echo '<pre>';
      print_r($json);
      echo '</pre>';
    } else {
      $this->response->setOutput(json_encode($json));
    }
  }


  public function verify_code() {
    $this->checkPlugin();

    if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
      $requestjson = file_get_contents('php://input');
      $requestjson = json_decode($requestjson, true);
      $post    = $requestjson;

      $this->load->language('account/register');
      $this->load->model('account/smsmobile');
      if($this->model_account_smsmobile->verifySmsCode($post['telephone'], $post['sms_code']) == 0) {
        $json["error"]["warning"] = $this->language->get('error_sms_code');
      }else{
        $json["success"]  = true;  
      }
    }else {
      $json["error"]["warning"]    = "Only POST request method allowed";
      $json["success"]  = false;
    }

    if ($this->debugIt) {
      echo '<pre>';
      print_r($json);
      echo '</pre>';
    } else {
      $this->response->setOutput(json_encode($json));
    }
  }

  public static function sendSms($appId, $appSecret, $templateId, $phone, $tempParam){
    date_default_timezone_set ( 'Asia/Shanghai' );
    if(is_array($tempParam)){
      $tempParam = json_encode($tempParam);
    }
    $timestamp = date ( 'Y-m-d H:i:s' );
    $grant_type = "client_credentials";
    // 获取Accesss Token
    $url = "https://oauth.api.189.cn/emp/oauth2/v3/access_token";
    $postdata = 'app_id=' . $appId . '&app_secret=' . $appSecret . '&grant_type=' . $grant_type;
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postdata );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    $data = curl_exec ( $ch );
    curl_close ( $ch );
    $data = json_decode ( $data, true );
    $access_token = $data ['access_token'];
    if(!$access_token){
      return "获取access_token失败: ".$data['res_message'];
    }
    // 发送模板短信
    $url = "http://api.189.cn/v2/emp/templateSms/sendSms";
    $postdata = 'timestamp=' . $timestamp . '&acceptor_tel=' . $phone . '&template_id=' . $templateId . '&template_param=' . $tempParam . '&app_id=' . $appId . '&access_token=' . $access_token;
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postdata );
    $data = curl_exec ( $ch );
    curl_close ( $ch );
    $data = json_decode ( $data, true );
    if ($data ['res_code'] === 0) {
        return 'successful';
    } else {
        return $data['res_message'];
    }
  }

  public static function sendSmsV2($appId, $appSecret, $templateId, $phone, $tempParam){

    $ret = array();
    date_default_timezone_set ( 'Asia/Shanghai' );
    if(is_array($tempParam)){
      $tempParam = json_encode($tempParam);
    }
    $timestamp = date ( 'Y-m-d H:i:s' );
    $grant_type = "client_credentials";
    // 获取Accesss Token
    $url = "https://oauth.api.189.cn/emp/oauth2/v3/access_token";
    $postdata = 'app_id=' . $appId . '&app_secret=' . $appSecret . '&grant_type=' . $grant_type;
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postdata );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    $ret['tokenReturn'] = curl_exec ( $ch );
    curl_close ( $ch );
    $data = json_decode ( $ret['tokenReturn'], true );
    $access_token = $data ['access_token'];
    if(!$access_token){
      $ret['returnStatus'] = "获取access_token失败: ".$data['res_message'];
      return $ret;
    }
    // 发送模板短信
    $url = "http://api.189.cn/v2/emp/templateSms/sendSms";
    $postdata = 'timestamp=' . $timestamp . '&acceptor_tel=' . $phone . '&template_id=' . $templateId . '&template_param=' . $tempParam . '&app_id=' . $appId . '&access_token=' . $access_token;
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postdata );
    $ret['sendReturn'] = curl_exec ( $ch );
    curl_close ( $ch );
    $data = json_decode ( $ret['sendReturn'], true );
    if ($data ['res_code'] === 0) {
      $ret['returnStatus'] = 'successful';
    } else {
      $ret['returnStatus'] = $data['res_message'];
    }
    return $ret;
  }
}

